//
//  SCPhotoSelectorViewController.swift
//  PhotoSelector
//
//  Created by newuser on 15/12/30.
//  Copyright © 2015年 newuser. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class SCPhotoSelectorViewController: UICollectionViewController {

    
    //MARK: - 属性
    ///保存用户选择照片
     var photos = [UIImage]()
    ///最大显示照片
    private var maxCount = 6
    
    //当前点击的cell
    private var currentIndexPath: NSIndexPath?
    
    //创建布局
    let layout =  UICollectionViewFlowLayout()
    
    init() {
    
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
      prepareCollectionView()
    }

    private func prepareCollectionView() {
    
    
        // 注册cell
        collectionView!.registerClass(SCPhotoSelectorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }


    //多少个
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return photos.count < maxCount ? photos.count + 1 : maxCount
    }

    //每行显示内容
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SCPhotoSelectorViewCell
        cell.cellDelegate = self
        
        //cell显示照片
        if indexPath.item < photos.count {
        
           cell.image = photos[indexPath.item]
        } else {
        
           cell.setAddButton()
        }
    
        return cell
    }

}

///扩展,实现cell的代理方法
extension SCPhotoSelectorViewController: SCPhotoSelectorViewCellDelegate {

    func cellAddButtonClick(cell: SCPhotoSelectorViewCell) {
       
        //获得某个的cell
        currentIndexPath = collectionView?.indexPathForCell(cell)
        //判断视图相册是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("系统相册不可用")
            return
        }
        //创建系统相册选择权
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        
        presentViewController(imagePicker, animated: true, completion: nil)
        
    }
    func cellRemoButtonClick(cell: SCPhotoSelectorViewCell) {
        //获取当前的cell
        let indexPath = collectionView?.indexPathForCell(cell)
        
        //删除在数组照片
        photos.removeAtIndex(indexPath!.item)
        
        //刷新
        collectionView?.reloadData()
    }

}

///MARK: - 扩展系统相册代理方法
extension SCPhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
   
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //用压缩的照片
        let newImage = image.scaleImage()
        
        //加号
        if currentIndexPath?.item == photos.count {
            //保存
            photos.append(newImage)
        } else {
          photos[currentIndexPath!.item] = newImage
        }
        
        
        //刷新
        collectionView?.reloadData()
        
        //去除控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

}


///cell的代理方法
@objc protocol SCPhotoSelectorViewCellDelegate: NSObjectProtocol {
    //定义方法,将自己传过去
    optional func cellAddButtonClick(cell: SCPhotoSelectorViewCell)
    optional func cellRemoButtonClick(cell: SCPhotoSelectorViewCell)
}


///自定义cell
class SCPhotoSelectorViewCell: UICollectionViewCell {

    
    //MARK: - 属性
    weak var cellDelegate: SCPhotoSelectorViewCellDelegate?

    
    
    var image: UIImage? {
        didSet {
             addButton.setImage(image, forState: UIControlState.Normal)
            //显示删除
            remoButton.hidden = false
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //坐标ui
        prepareUI()
    }

    
    func prepareUI() {
       //添加UI
        contentView.addSubview(addButton)
        contentView.addSubview(remoButton)
        
        //添加约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        remoButton.translatesAutoresizingMaskIntoConstraints = false
        
       contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab" : addButton]))
        
        //删除
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb" : remoButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb" : remoButton]))
    
    }
    
    ///设置加号按钮
    func setAddButton() {
       addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        //隐藏删除
        remoButton.hidden = true
    }
    
    
    //MARK: - 懒加载
    private lazy var addButton: UIButton = {
    
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        //模式
        button.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
        
        button.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    
    }()
    
    private lazy var remoButton: UIButton = {
    
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)

           button.addTarget(self, action: "remoButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    //MARK: - 点击事件
    func addButtonClick() {
      cellDelegate?.cellAddButtonClick?(self)
    }
    
    func remoButtonClick() {
    cellDelegate?.cellRemoButtonClick?(self)
    }
    
}


